//
//  LHRadioDetailViewController.m
//  EPA
//
//  Created by 卢浩 on 16/4/21.
//  Copyright © 2016年 卢浩. All rights reserved.
//

#import "LHRadioDetailViewController.h"
#import "LHRadioListModel.h"
#import "LHRadioDetailModel.h"
#import "LHAVPlayerManager.h"
#import <AVFoundation/AVFoundation.h>
#import "LHMenuViewController.h"
#import "LHRadioDownloadManager.h"

@interface LHRadioDetailViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) NSMutableArray *itemsArray;

@property (nonatomic,strong) NSMutableArray *radioDetailArray;

@property (nonatomic,strong) NSTimer *timer;

@property (weak, nonatomic) IBOutlet UISlider *rateSlider;

@property (weak, nonatomic) IBOutlet UILabel *currentLable;

@property (weak, nonatomic) IBOutlet UILabel *allTimeLable;

@property (weak, nonatomic) IBOutlet UIButton *playOrStopBtn;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (nonatomic,strong) UIImageView *imageView;

@property (nonatomic,strong) UIWebView *webView;

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) UIBarButtonItem *downloadBarBtn;

@end

static BOOL isShow;

static LHRadioDetailViewController *radioDetailVC;

@implementation LHRadioDetailViewController

- (UIBarButtonItem *)downloadBarBtn{
    if (_downloadBarBtn == nil) {
        _downloadBarBtn = [[UIBarButtonItem alloc]initWithTitle:@"下载" style:(UIBarButtonItemStylePlain) target:self action:@selector(downloadAction)];
    }
    return _downloadBarBtn;
}

- (void)downloadAction{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否下载此电台?" preferredStyle:(UIAlertControllerStyleAlert)];
    [alertController addAction:[UIAlertAction actionWithTitle:@"下载" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [[LHRadioDownloadManager shareManager] addDownloadTaskWithModel:self.radioDetailArray[self.index] ProgressBlock:nil CompleteBlock:nil];
        self.downloadBarBtn.title = @"已下载";
        self.downloadBarBtn.enabled = NO;
        self.downloadBarBtn.tintColor = [UIColor whiteColor];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self replaceBarbtn];
}

- (void)replaceBarbtn{
    
    NSString *title = [self.radioDetailArray[self.index] title];
    NSString *urlName  = [[self.radioDetailArray[self.index] musicUrl] stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
    urlName = [urlName stringByReplacingOccurrencesOfString:@":" withString:@"_"];
    NSString *nowMp3Name = [title stringByAppendingString:[NSString stringWithFormat:@"|%@",urlName]];
//    NSLog(@"%@",nowMp3Name);
    
    BOOL isHave = NO;
    for (NSString *mp3Name in [LHRadioDownloadManager shareManager].tempDownloadArr) {
        if ([mp3Name isEqualToString:nowMp3Name]) {
            isHave = YES;
        }
    }
    if (isHave) {
        self.downloadBarBtn.title = @"已下载";
        self.downloadBarBtn.enabled = NO;
        self.downloadBarBtn.tintColor = [UIColor whiteColor];
    }else{
        self.downloadBarBtn.title = @"下载";
        self.downloadBarBtn.enabled = YES;
        self.downloadBarBtn.tintColor = nil;
    }
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    isShow = YES;
    radioDetailVC = self;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    isShow = NO;
    radioDetailVC = nil;
}

- (NSMutableArray *)itemsArray{
    if (_itemsArray == nil) {
        _itemsArray = [NSMutableArray array];
    }
    return _itemsArray;
}

- (NSMutableArray *)radioDetailArray{
    if (_radioDetailArray == nil) {
        _radioDetailArray = [NSMutableArray array];
    }
    return _radioDetailArray;
}

- (void)setRadioArray:(NSMutableArray *)radioArray{
    if (_radioArray != radioArray) {
        _radioArray = radioArray;
    }
    if (_radioArray.count > 0) {
        [self.radioDetailArray removeAllObjects];
        [self.itemsArray removeAllObjects];
        for (LHRadioListModel *model in _radioArray) {
            LHRadioDetailModel *detailModel = model.radioDetailModel;
            [self.radioDetailArray addObject:detailModel];
            AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:detailModel.musicUrl]];
//            NSLog(@"%@",detailModel.musicUrl);
            [self.itemsArray addObject:item];
        }
    }
}

- (void)setRadioid:(NSString *)radioid{
    if (_radioid != radioid) {
        _radioid = radioid;
    }
    [LHAVPlayerManager shareInstant].radioid = _radioid;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(self.view.frame.size.width - 10, 0, self.view.frame.size.width - 10, self.view.frame.size.height - 210)];
    if (view1.frame.size.height > view1.frame.size.width) {
        self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(view1.frame.size.width * 0.05, (view1.frame.size.height - view1.frame.size.width * 0.9) / 2, view1.frame.size.width * 0.9, view1.frame.size.width * 0.9)];
        self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2;
    }else if (view1.frame.size.height < view1.frame.size.width){
        self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake((view1.frame.size.width - view1.frame.size.height * 0.9) / 2, view1.frame.size.height * 0.05, view1.frame.size.height * 0.9, view1.frame.size.height * 0.9)];
        self.imageView.layer.cornerRadius = self.imageView.frame.size.height / 2;
    }
    
    self.imageView.layer.masksToBounds = YES;
    [view1 addSubview:self.imageView];
    
    UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(view1.frame.size.width * 2, 0, view1.frame.size.width, view1.frame.size.height)];
    self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(5, 5, view2.frame.size.width - 10, view2.frame.size.height - 10)];
    [view2 addSubview:self.webView];
    
    UIView *view3 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, view1.frame.size.width, view1.frame.size.height)];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(5, 5, view3.frame.size.width - 10, view3.frame.size.height - 10)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [view3 addSubview:self.tableView];
    
    [self.scrollView addSubview:view3];
    [self.scrollView addSubview:view1];
    [self.scrollView addSubview:view2];
    
    self.scrollView.pagingEnabled = YES;
    self.scrollView.contentSize =CGSizeMake(view1.frame.size.width * 3, 0);
    self.scrollView.contentOffset = CGPointMake(view1.frame.size.width, 0);
    self.scrollView.showsHorizontalScrollIndicator = NO;
    
    [self setTitleAndImageViewAndWebView];
    
    [self addTimer];
    
    //添加动画效果
    [LHMenuViewController rotate360DegreeWithImageView:self.imageView];
    
    //给AVPlayerManager传递数据
    [LHAVPlayerManager shareInstant].itemsArray = self.itemsArray;
    [LHAVPlayerManager shareInstant].radioDetailArray = self.radioDetailArray;
    if ([LHAVPlayerManager shareInstant].currentIndex != self.index) {
        [LHAVPlayerManager shareInstant].currentIndex = self.index;
        [[LHAVPlayerManager shareInstant] replaceMusic];
        [self setLeftMenuMusicView];
    }
    
    self.navigationItem.rightBarButtonItem = self.downloadBarBtn;
}

//添加计时器
- (void)addTimer{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

//计时器方法
- (void)timerAction{
    //当前时间
    CGFloat currentTime = 0;
    if ([LHAVPlayerManager shareInstant].avPlayer.currentTime.timescale > 0) {
        currentTime = [LHAVPlayerManager shareInstant].avPlayer.currentTime.value / [LHAVPlayerManager shareInstant].avPlayer.currentTime.timescale;
    }
    self.currentLable.text = [NSString stringWithFormat:@"%02d:%02d",(int)currentTime/60,(int)currentTime%60];
    
    //总时间
    CGFloat allTime = 0;
    if ([LHAVPlayerManager shareInstant].avPlayer.currentItem.duration.timescale != 0) {
        allTime = [LHAVPlayerManager shareInstant].avPlayer.currentItem.duration.value / [LHAVPlayerManager shareInstant].avPlayer.currentItem.duration.timescale;
    }
    self.allTimeLable.text = [NSString stringWithFormat:@"%02d:%02d",(int)allTime/60,(int)allTime%60];
    
    //改变进度条位置
    if (currentTime > 0 && allTime > 0) {
        self.rateSlider.value = currentTime / allTime;
    }
    
    //刷新播放按钮图片,外部链接改变时,同步改变
    if ([LHAVPlayerManager shareInstant].avPlayer.rate == 0) {
        [self.playOrStopBtn setBackgroundImage:[UIImage imageNamed:@"AV播放"] forState:(UIControlStateNormal)];
    }else if ([LHAVPlayerManager shareInstant].avPlayer.rate == 1){
        [self.playOrStopBtn setBackgroundImage:[UIImage imageNamed:@"AV暂停"] forState:(UIControlStateNormal)];
    }
    
    if (self.scrollView.contentOffset.x != 0) {
        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:self.index inSection:0] animated:YES scrollPosition:(UITableViewScrollPositionMiddle)];
    }
}

+ (void)replaceTitleAndImageViewAndWebView{
    if (isShow) {
        [radioDetailVC setTitleAndImageViewAndWebView];
    }
}

//设置页面的标题,图片跟网页
- (void)setTitleAndImageViewAndWebView{
    self.navigationItem.title = [self.radioDetailArray[self.index] title];
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:[self.radioDetailArray[self.index] imgUrl]]];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[self.radioDetailArray[self.index] webview_url]]]];
    self.rateSlider.value = 0;
    
    //更新下载按钮
    [self replaceBarbtn];
}

//播放暂停
- (IBAction)playOrStopAction:(UIButton *)sender {
    if ([LHAVPlayerManager shareInstant].avPlayer.rate == 0) {
        [[LHAVPlayerManager shareInstant] play];
        [sender setBackgroundImage:[UIImage imageNamed:@"AV暂停"] forState:(UIControlStateNormal)];
    }else if([LHAVPlayerManager shareInstant].avPlayer.rate == 1){
        [[LHAVPlayerManager shareInstant] pause];
        [sender setBackgroundImage:[UIImage imageNamed:@"AV播放"] forState:(UIControlStateNormal)];
    }
}

//下一曲
- (IBAction)nextAction:(UIButton *)sender {
    self.index ++;
    if (self.index > self.radioDetailArray.count - 1) {
        self.index = 0;
    }
    [self setTitleAndImageViewAndWebView];
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:self.index inSection:0] animated:YES scrollPosition:(UITableViewScrollPositionMiddle)];
    [self.playOrStopBtn setBackgroundImage:[UIImage imageNamed:@"AV暂停"] forState:(UIControlStateNormal)];
    [[LHAVPlayerManager shareInstant] next];
}

//上一曲
- (IBAction)lastAction:(UIButton *)sender {
    self.index --;
    if (self.index < 0) {
        self.index = self.radioDetailArray.count - 1;
    }
    [self setTitleAndImageViewAndWebView];
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:self.index inSection:0] animated:YES scrollPosition:(UITableViewScrollPositionMiddle)];
    [self.playOrStopBtn setBackgroundImage:[UIImage imageNamed:@"AV暂停"] forState:(UIControlStateNormal)];
    [[LHAVPlayerManager shareInstant] last];
}

//进度条变化
- (IBAction)rateChangedAction:(UISlider *)sender {
    CGFloat allTime;
    if ([LHAVPlayerManager shareInstant].avPlayer.currentItem.duration.timescale != 0) {
        allTime = [LHAVPlayerManager shareInstant].avPlayer.currentItem.duration.value / [LHAVPlayerManager shareInstant].avPlayer.currentItem.duration.timescale;
    }
    [[LHAVPlayerManager shareInstant] seekToTime:CMTimeMake([LHAVPlayerManager shareInstant].avPlayer.currentTime.timescale * allTime * sender.value, [LHAVPlayerManager shareInstant].avPlayer.currentTime.timescale)];
    [[LHAVPlayerManager shareInstant] play];
}

//设置左侧抽屉的音乐栏内容
- (void)setLeftMenuMusicView{
    LHRadioDetailModel *model = self.radioDetailArray[self.index];
    [[LHMenuViewController getMenuViewController] setMusicViewWithTitle:model.title Desc:model.userinfo[@"uname"] Img:model.imgUrl];
}

//外部链接的上一曲
+ (void)nextMusic{
    if (isShow) {
        [radioDetailVC nextAction:nil];
    }else{
        [[LHAVPlayerManager shareInstant] next];
    }
}

//外部链接的下一曲
+ (void)lastMusic{
    if (isShow) {
        [radioDetailVC lastAction:nil];
    }else{
        [[LHAVPlayerManager shareInstant] last];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.radioDetailArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"cell"];
    }
    cell.textLabel.text = [self.radioDetailArray[indexPath.row] title];
    cell.detailTextLabel.text = [self.radioDetailArray[indexPath.row] userinfo][@"uname"];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    self.index = indexPath.row;
    [self setTitleAndImageViewAndWebView];
    [LHAVPlayerManager shareInstant].currentIndex = indexPath.row;
    [[LHAVPlayerManager shareInstant] seekToTime:CMTimeMake(0, 1)];
    [[LHAVPlayerManager shareInstant] replaceMusic];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
